package com.note.chh.notebook.UI.homeFragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.blankj.utilcode.util.NetworkUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.note.chh.notebook.Adapter.EnjoyAdapter;
import com.note.chh.notebook.Api.Constant;
import com.note.chh.notebook.Model.BeautifulPictureModel;
import com.note.chh.notebook.Model.EnjoyModel;
import com.note.chh.notebook.R;
import com.note.chh.notebook.UI.base.BaseFragment;
import com.note.chh.notebook.UI.enjoy.AIActivity;
import com.note.chh.notebook.UI.enjoy.BeautifulPictureActivity;
import com.note.chh.notebook.UI.enjoy.CheckMusicPictureActivity;
import com.note.chh.notebook.UI.enjoy.DoodleViewActivity;
import com.note.chh.notebook.UI.enjoy.MusicActivity;
import com.note.chh.notebook.UI.enjoy.NetMusicActivity;
import com.note.chh.notebook.UI.enjoy.VideoActivity;
import com.note.chh.notebook.UI.enjoy.VideoColletionActivity;
import com.note.chh.notebook.UI.enjoy.WeatherActivity;
import com.note.chh.notebook.Uitls.GlideImageLoader;
import com.note.chh.notebook.Uitls.gson.GsonImpl;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;

/**
 * 娱乐 fragment
 */
public class EnjoyFragment extends BaseFragment {


    @BindView(R.id.mRecycle_enjoy)
    RecyclerView mRecycleEnjoy;

    private List<EnjoyModel> enjoyList;
    private BaseQuickAdapter enjoyAdapter;
    private Banner banner;
    private View inflate;
    private List<BeautifulPictureModel.ResultsBean> results;
    private List<String> imgList;

    private boolean isMobileData = false;//是否移动网络

    public EnjoyFragment() {
        // Required empty public constructor
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_enjoy;
    }

    @Override
    public void initView(View view) {
        mRecycleEnjoy.setLayoutManager(new GridLayoutManager(getActivity(),4));
        mRecycleEnjoy.setHasFixedSize(true);
        enjoyAdapter = new EnjoyAdapter(R.layout.item_enjoy);
        enjoyAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleEnjoy.setAdapter(enjoyAdapter);
    }

    @Override
    public void initData() {
        if (enjoyList == null) {
            enjoyList = new ArrayList<>();
        }
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_music,getResources().getString(R.string.music),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_video,getResources().getString(R.string.video),getResources().getColor(R.color.pale_dogwood)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_weather,getResources().getString(R.string.weather),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_drawing,getResources().getString(R.string.doodle_view),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_beautiful,getResources().getString(R.string.beautiful),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_video_colletion,getResources().getString(R.string.videoColletion),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_net_music,getResources().getString(R.string.net_music),getResources().getColor(R.color.whiteBg)));
        enjoyList.add(new EnjoyModel(R.mipmap.enjoy_ai,getResources().getString(R.string.ai),getResources().getColor(R.color.whiteBg)));

//        enjoyAdapter.addHeaderView()

        getBPlist();

        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.layout_banner, null);
        banner = inflate.findViewById(R.id.banner);

    }

    @Override
    public void initListener() {
        super.initListener();
        enjoyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EnjoyModel enjoyModel = enjoyList.get(position);
                switch (enjoyModel.getName()){
                    case "本地音乐":
                        startActivity(MusicActivity.class);
                        break;
                    case "本地视频":
                        startActivity(VideoActivity.class);
                        break;
                    case "天气":
                        startActivity(WeatherActivity.class);
                        break;
                    case "绘画板":
                        startActivity(DoodleViewActivity.class);
                        break;
                    case "美图":
//                        if (NetworkUtils.isMobileData()) {//判断是否是移动数据
//                            showConfirmMessageDialog();
//                        }else{
                            startActivity(BeautifulPictureActivity.class);
//                        }
                        break;
                    case "视频集":
                        startActivity(VideoColletionActivity.class);
                        break;
                    case "网络音乐":
                        startActivity(NetMusicActivity.class);
                        break;
                    case "AI小萌":
                        startActivity(AIActivity.class);
                        break;
                }
            }
        });
    }

    //确认弹窗 --- 网络监测
    private void showConfirmMessageDialog() {
        final QMUIDialog.CheckBoxMessageDialogBuilder dialogBuilder = new QMUIDialog.CheckBoxMessageDialogBuilder(getActivity());
        dialogBuilder
                .setTitle("非WIFI连接，继续将使用流量")
//                .setMessage("当前您处于数据网络连接，继续将使用流量,是否继续?")
                .setMessage("下次不再提示")
                .setChecked(false)
                .addAction("心疼流量", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("我流量多", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                       showToast(""+ dialogBuilder.isChecked());
                        dialog.dismiss();
                    }
                })
                .show();
    }

    //获取banner图
    private void getBPlist() {
        Random random = new Random();
        int nextInt = random.nextInt(60);
        OkGo.<String>get("http://gank.io/api/data/福利/" + 10 + "/" + nextInt)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

//                UserUtil.dLog(" response = "+response.body());
                        BeautifulPictureModel beautifulPictureModel = GsonImpl.get().toObject(response.body(), BeautifulPictureModel.class);
                        results = beautifulPictureModel.getResults();

                        enjoyAdapter.setNewData(enjoyList);
                        imgList = new ArrayList<>();
                        for (int i = 0; i < results.size(); i++) {
                            imgList.add(results.get(i).getUrl());
                        }
                        setBannerData(imgList);
                        enjoyAdapter.addHeaderView(inflate);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        //数据请求错误时设置列表数据
                        enjoyAdapter.setNewData(enjoyList);
                        //网络不通
                        if (!NetworkUtils.isAvailableByPing()) {
                            showToast(Constant.NETWORKNOUSER);
                        }
                    }
                });
    }


    //设置banner数据
    private void setBannerData(List<String> images){
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置指示器
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.CubeOut);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //点击事件
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getActivity(), CheckMusicPictureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("picUrl", results.get(position).getUrl());
                bundle.putString("picName", "/" + results.get(position).get_id() + ".png");
                bundle.putString("picFolder", Constant.girlImageSaveFolder);
                intent.putExtras(bundle);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.scale_in, R.anim.alpha_out);
            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        if (banner!=null) {
            banner.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        if (banner!=null) {
            banner.stopAutoPlay();
        }
    }
}
